<?php
namespace app\admin\controller;
use app\admin\model\Member;

/**
 * 用户管理
 * Class Member
 */
class MemberController extends BaseController {

    protected function _initialize() {
        parent::_initialize();
    }

    /**
     * 用户管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index($keyword = '', $ziduan = 'a.id', $param='a.add_time', $sort='desc') {
        $map = [];
		$order = $param. ' '.$sort;
		$this->assign('param', $param);
		$this->assign('sort', $sort);
        if ($keyword) {
            $map[$ziduan] = $keyword;
        }
		$this->assign('ziduan', $ziduan);
		$res = db('member')->field('count(id) as count,level')->group('level')->buildSql();
		
        $member_list = db('member')->alias('a')
					->join($res.' b','a.id = b.level','LEFT')
					->field('a.*,b.count')
					->where($map)->order($order)->paginate(15, false, get_query());
        return $this->fetch('index', ['member_list' => $member_list, 'keyword' => $keyword]);
    }
	
    /**
     * 添加用户
     * @return mixed
     */
    public function add() {
        return $this->fetch();
    }
	/**
	 * 用户收货地址
	 */
	public function address(){
		$list=db("member_address")->paginate(15);
		$this->assign('list',$list);
		return $this->fetch();
	}
    /**
     * 保存用户
     */
    public function save() {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
        	$password = $data['password'];
            $data['password'] = md5_salt($password);
			$data['add_time'] = now_time();
			$member_model = new Member();
            if ($member_model->allowField(true)->save($data)) {
                $this->success('添加成功',url("index"));
            } else {
                $this->error('添加失败');
            }
        }
    }

    /**
     * 编辑用户
     * @param $id
     * @return mixed
     */
    public function edit($id) {
    	$member_model = new Member();
        $member = $member_model->where('id',$id)->find();
        return $this->fetch('edit', ['member' => $member]);
    }

    /**
     * 更新用户
     * @param $id
     */
    public function update($id) {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            if (!empty($data['password'])) {
                $data['password'] = md5_salt($data['password']);
            }else{
            	$data['password'] = $data['old_pwd'];
            }

			$member_model = new Member();
            if ($member_model->allowField(true)->save($data,['id'=>$id]) !== false) {
                $this->success('更新成功',url("index"));
            } else {
                $this->error('更新失败');
            }
        }
    }
	
	//删除会员
	public function delete_item(){
		$res = db('member')->where('id',input("id"))->delete();
		if($res){
			 $this->success('删除成功',url("index"));
		}else{
			 $this->success('删除失败');
		}
	}

}
